package logic

import (
	"context"
	"errors"
	"videos/model/mysql"

	"videos/videorpc/internal/svc"
	"videos/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateNickNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateNickNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateNickNameLogic {
	return &UpdateNickNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateNickNameLogic) UpdateNickName(in *videorpc.UpdateNickNameRequest) (*videorpc.UpdateNickNameResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	err := user.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}

	if user.ID == 0 {
		return nil, errors.New("该用户不存在")
	}

	if user.NickName == in.NickName {
		return nil, errors.New("旧昵称和新昵称一致,不允许修改")
	}

	user.NickName = in.NickName

	err = user.UpdateNickName(mysql.DB)
	if err != nil {
		return nil, err
	}

	return &videorpc.UpdateNickNameResponse{
		UserId: int64(user.ID),
	}, nil
}
